//
//  CXDetailFirstViewController.m
//  ProjectOfBStage
//
//  Created by cuixin on 15/11/14.
//  Copyright © 2015年 cuixin. All rights reserved.
//

#import "CXDetailFirstViewController.h"
#import "CustomerNetworking.h"
#import "CXCustomerNavigationBar.h"
#import "CXFirstDetailModel.h"
#import "CXFirstDetailCollectionViewCell.h"
#import <SDWebImageManager.h>
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import <STKAudioPlayer.h>
#import "LDY_HeaderView.h"
#define ImageHight 200.0f
#import "BaseHeader.h"
#import "FZ_Dounment.h"
#import "CoreDataManager.h"
#import "LDY_PlayViewController.h"
#import "DatabaseHandler.h"
#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height
#define WIDTH self.view.frame.size.width
#define HEIGHT 180


#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#define WIDTH_PRO(X) (X)*(SCREEN_WIDTH/375)

#define HEIGHT_PRO(Y) (Y)*(SCREEN_HEIGHT/667)



@interface CXDetailFirstViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>

@property(nonatomic, retain)NSMutableArray *array;
@property(nonatomic, retain)NSMutableArray *secondArray;
@property(nonatomic, retain)UIImageView *image;
@property(nonatomic, retain)CXCustomerNavigationBar *navigationBar;
@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, retain)UICollectionView *secondCollectionView;
@property(nonatomic, retain)UIScrollView *scrollView;
@property(nonatomic, retain)LDY_HeaderView *headerView;
@property (nonatomic ,retain) CXFirstDetailModel *coreModel;
@property(nonatomic, retain)CoreDataManager *manager;
@property(nonatomic, retain)NSArray *coreArray;
@property (nonatomic, retain)NSArray *tempArray;

@end

@implementation CXDetailFirstViewController

-(void)dealloc{
    [_array release];
    [_collectionView release];
    [_image release];
    [_navigationBar release];
    [_scrollView release];
    [_secondCollectionView release];
    [_secondArray release];
    [_headerView release];
    [_coreModel release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    
    self.secondArray = [NSMutableArray array];
    self.array = [NSMutableArray array];
    [self createScrollView];
    [self createCollectionView];
    [self createSecondCollectionView];
    [self createCustomerNavigationBar];
    
    [self header];
    [self footer];
    [self secondHeader];
    [self secondFooter];
    
    self.manager = [CoreDataManager shareManager];
    
//    [[DatabaseHandler shareDatabaseHandler] openDB];
//    
//    [[DatabaseHandler shareDatabaseHandler] createHistoryHomeTable:@"saveHistoryFisrt"];
}
-(void)createScrollView{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight )];
    self.scrollView.delegate = self;
    self.scrollView.contentSize = CGSizeMake(kWidth * 2, 0);
    self.scrollView.bounces = NO;
    self.scrollView.scrollEnabled = NO;

    [self.view addSubview:self.scrollView];
    [_scrollView release];
}

-(void)header{
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        self.loading =NO;
        [self loadData:self.page andLoading:NO];
        self.collectionView.header.hidden = NO;
    }];
    [self.collectionView.header beginRefreshing];
    
}
-(void)footer{
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page ++;
        self.loading = YES;
        [self loadData:self.page andLoading:YES];
    }];
}
-(void)secondHeader{
    self.secondCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        self.loading =NO;
        [self loadSecondData:self.page andLoading:NO];
        self.secondCollectionView.header.hidden = YES;
    }];
    [self.secondCollectionView.header beginRefreshing];
}
-(void)secondFooter{
    self.secondCollectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page ++;
        self.loading = YES;
        [self loadSecondData:self.page andLoading:YES];
    }];
}
#pragma mark 解析数据
-(void)loadData:(NSInteger)page andLoading:(BOOL)loading{
    NSString *frontUrl = @"http://echosystem.kibey.com/channel/info?limit=20&id=";
    NSString *lastUrl = @"&list_order=hot&page=";
    NSString *totalUrl = [NSString stringWithFormat:@"%@%@%@%ld", frontUrl, self.detailID, lastUrl, page];
    NSLog(@"%@", totalUrl);
    [CustomerNetworking customerWithURL:totalUrl andParamer:nil andBlock:^(id response) {
        if (loading == NO) {
            [self.array removeAllObjects];
        }
        for (NSDictionary *dic in [[[response objectForKey:@"result"] objectForKey:@"data"] objectForKey:@"sounds"]) {
            CXFirstDetailModel *model = [CXFirstDetailModel modelWithDictionary:dic];
            [self.array addObject:model];
        }
        [self.collectionView reloadData];
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        self.collectionView.header.hidden = YES;
    }];
}

#pragma mark 创建collectionView
-(void)createCollectionView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) collectionViewLayout:flowLayout];
    self.collectionView.contentInset=UIEdgeInsetsMake(HEIGHT_PRO(HEIGHT), 0, 0, 0);
    
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = HEIGHT_PRO(5);
    flowLayout.itemSize = CGSizeMake(WIDTH_PRO(180), HEIGHT_PRO(200));
    flowLayout.sectionInset = UIEdgeInsetsMake(HEIGHT_PRO(ImageHight) + HEIGHT_PRO(15), WIDTH_PRO(5), 0, WIDTH_PRO(5));
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:[CXFirstDetailCollectionViewCell class] forCellWithReuseIdentifier:@"CXFirstDetailCollectionViewCellID"];
    [self.scrollView addSubview:self.collectionView];
    
    self.headerView = [[LDY_HeaderView alloc] initWithFrame:CGRectMake(0, 0, kWidth, HEIGHT)];
    [self.headerView.headerView sd_setImageWithURL:[NSURL URLWithString:self.bigImage]];
    
    [self.collectionView addSubview:self.headerView];
    [_headerView release];
}

#pragma mark 解析第二个segment的数据
-(void)loadSecondData:(NSInteger)page andLoading:(BOOL)loading{
    
//    1091&list_order=news&page=1
    NSString *frontUrl = @"http://echosystem.kibey.com/channel/info?limit=20&id=";
    NSString *lastUrl = @"&list_order=news&page=";
    NSString *totalUrl = [NSString stringWithFormat:@"%@%@%@%ld", frontUrl, self.detailID, lastUrl, page];
    
    [CustomerNetworking customerWithURL:totalUrl andParamer:nil andBlock:^(id response) {
        if (loading == NO) {
            [self.secondArray removeAllObjects];
        }
        for (NSDictionary *dic in [[[response objectForKey:@"result"] objectForKey:@"data"] objectForKey:@"sounds"]) {
            CXFirstDetailModel *model = [CXFirstDetailModel modelWithDictionary:dic];
            [self.secondArray addObject:model];
        }
        [self.secondCollectionView reloadData];
        [self.secondCollectionView.header endRefreshing];
        [self.secondCollectionView.footer endRefreshing];
    }];
}

-(void)createSecondCollectionView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.secondCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(kWidth, 0, kWidth, kHeight) collectionViewLayout:flowLayout];

    self.secondCollectionView.contentInset=UIEdgeInsetsMake(HEIGHT_PRO(ImageHight), 0, 0, 0);
    self.secondCollectionView.backgroundColor = [UIColor redColor];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = HEIGHT_PRO(5);
    flowLayout.itemSize = CGSizeMake(WIDTH_PRO(180), HEIGHT_PRO(200));
    flowLayout.sectionInset = UIEdgeInsetsMake(HEIGHT_PRO(ImageHight) + HEIGHT_PRO(15), WIDTH_PRO(5), 0, WIDTH_PRO(5));
    self.secondCollectionView.delegate = self;
    self.secondCollectionView.dataSource = self;
    self.secondCollectionView.backgroundColor = [UIColor whiteColor];
    [self.secondCollectionView registerClass:[CXFirstDetailCollectionViewCell class] forCellWithReuseIdentifier:@"CXFirstDetailCollectionViewCellID"];
    [self.scrollView addSubview:self.secondCollectionView];
    
    
    self.image = [[UIImageView alloc] init];
    self.image.frame=CGRectMake(0, 0, self.view.frame.size.width, HEIGHT_PRO(ImageHight));
    [self.image sd_setImageWithURL:[NSURL URLWithString:self.bigImage]];
    //    self.image.contentMode=UIViewContentModeScaleAspectFill;//不设置只会被纵向拉抻
    
    [self.secondCollectionView addSubview:self.image];
    [_image release];
    
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if ([[NSString stringWithFormat:@"%@",[scrollView class]] isEqualToString:@"UIScrollView"]) {
        self.navigationBar.segment.selectedSegmentIndex = scrollView.contentOffset.x / kWidth;
    }
    CGFloat y=scrollView.contentOffset.y;
    
    //设置图片的变化
    if (scrollView == self.collectionView) {
        CGFloat dy = scrollView.contentOffset.y;
        if (dy < 0) {
            self.headerView.headerView.frame = CGRectMake(-(-(dy) * WIDTH / HEIGHT_PRO(HEIGHT)) / 2, dy, WIDTH - (dy) * WIDTH / HEIGHT_PRO(HEIGHT) , HEIGHT_PRO(HEIGHT) - dy);
        }
    }
    if (scrollView == self.secondCollectionView) {
        CGFloat dy = scrollView.contentOffset.y;
        if (dy < 0) {
            self.image.frame = CGRectMake(-(-(dy) * kWidth / HEIGHT_PRO(ImageHight)) / HEIGHT_PRO(2), dy, kWidth - (dy) * kWidth / HEIGHT_PRO(ImageHight), HEIGHT_PRO(ImageHight) - dy);
        }
    }

    //设置自定义navigationBar的状态
    if (y > HEIGHT_PRO(200)) {
        self.navigationBar.backView.backgroundColor = [UIColor blackColor];
        self.navigationBar.backView.alpha = 0.7;
        self.navigationBar.titleLabe.hidden = YES;
        self.navigationBar.segment.hidden = NO;
        self.navigationBar.segment.tintColor = [UIColor whiteColor];
        
    }else{
        self.navigationBar.titleLabe.hidden = NO;
        self.navigationBar.segment.hidden = YES;
        self.navigationBar.backView.backgroundColor = [UIColor clearColor];
    }
    
}


#pragma mark 创建自定义navigationBar
-(void)createCustomerNavigationBar{
    self.navigationBar = [[CXCustomerNavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, HEIGHT_PRO(60))];
    [self.navigationBar.segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self.navigationBar.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBar.playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationBar.titleLabe.text = self.name;
    [self.view addSubview:self.navigationBar];
    [self.navigationBar release];
}

#pragma mark segment的点击事件
-(void)segmentAction:(UISegmentedControl *)segment{
    //    self.scrollView.contentOffset = CGPointMake(kWidth * segment.selectedSegmentIndex, 0);
    switch (segment.selectedSegmentIndex) {
        case 0:
            self.scrollView.contentOffset = CGPointMake(0, 0);
            break;
        case 1:
            self.scrollView.contentOffset = CGPointMake(kWidth, 0);
        default:
            break;
    }
    
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == self.collectionView) {
        return self.array.count;
    }else{
        return self.secondArray.count;
    }
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.collectionView) {
        CXFirstDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CXFirstDetailCollectionViewCellID" forIndexPath:indexPath];
        CXFirstDetailModel *model = [self.array objectAtIndex:indexPath.row];
        cell.detailModel = model;
        return cell;
    }else{
        CXFirstDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CXFirstDetailCollectionViewCellID" forIndexPath:indexPath];
        CXFirstDetailModel *model = [self.secondArray objectAtIndex:indexPath.row];
        cell.detailModel = model;
        
        return cell;
        
    }
}
#pragma mark collectionView的点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.collectionView) {
        LDY_PlayViewController *playController = [LDY_PlayViewController sharePlayer];
        [[LDY_PlayViewController sharePlayer] setData:self.array row:indexPath.row];
        CXFirstDetailModel *model = [self.array objectAtIndex:indexPath.row];
        //传参数
        playController.detailModel = model;
        playController.name = model.name;
        playController.pic = model.pic;
        playController.playUrl = model.source;
        playController.indexRow = indexPath.row;

        [self searchHistory];
        int count = 0;
        if (self.tempArray.count == 0) {
            FZ_Dounment *list = [NSEntityDescription insertNewObjectForEntityForName:@"FZ_Dounment" inManagedObjectContext:self.manager.managedObjectContext];
            list.name = model.name;
            list.pic = model.pic;
            list.source = model.source;
            [self.manager saveContext];
        }
        else{
            for (FZ_Dounment *modelll in self.tempArray) {
                if (![modelll.source isEqualToString:model.source]) {
                    count++;
                }
            }
            if (count == self.tempArray.count) {
                FZ_Dounment *list = [NSEntityDescription insertNewObjectForEntityForName:@"FZ_Dounment" inManagedObjectContext:self.manager.managedObjectContext];
                list.name = model.name;
                list.pic = model.pic;
                list.source = model.source;

                [self.manager saveContext];
            }
        }


        [self.navigationController pushViewController:playController animated:YES];
//        [playController release];
    }else{
        [[LDY_PlayViewController sharePlayer] setData:self.secondArray row:indexPath.row];
        LDY_PlayViewController *playController = [LDY_PlayViewController sharePlayer];
        CXFirstDetailModel *model = [self.secondArray objectAtIndex:indexPath.row];
        playController.playUrl = model.source;
        playController.name = model.name;
        playController.pic = model.pic;
        playController.detailModel = model;
        playController.indexRow = indexPath.row;
        
        [self searchHistory];
        int count = 0;
        if (self.tempArray.count == 0) {
            FZ_Dounment *list = [NSEntityDescription insertNewObjectForEntityForName:@"FZ_Dounment" inManagedObjectContext:self.manager.managedObjectContext];
            list.name = model.name;
            list.pic = model.pic;
            list.source = model.source;
            [self.manager saveContext];
        }
        else{
            for (FZ_Dounment *modelll in self.tempArray) {
                if (![modelll.source isEqualToString:model.source]) {
                    count++;
                }
            }
            if (count == self.tempArray.count) {
                FZ_Dounment *list = [NSEntityDescription insertNewObjectForEntityForName:@"FZ_Dounment" inManagedObjectContext:self.manager.managedObjectContext];
                list.name = model.name;
                list.pic = model.pic;
                list.source = model.source;
                
                [self.manager saveContext];
            }
        }

        playController.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:playController animated:YES];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
}
#pragma mark 自定义navigationBar返回按钮的点击事件
-(void)backButtonAction:(UIButton *)button{
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark 播放按钮点击事件
-(void)playButtonAction:(UIButton *)button{
    LDY_PlayViewController *play = [LDY_PlayViewController sharePlayer];
    if (play.player.state == STKAudioPlayerStatePaused) {

    }
    play.hidesBottomBarWhenPushed = YES;
    self.navigationController.navigationBarHidden = YES;
    [self.navigationController pushViewController:play animated:YES];
}

-(void)searchHistory{
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"FZ_Dounment" inManagedObjectContext:self.manager.managedObjectContext];
        [fetchRequest setEntity:entity];
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"source"
                                                                       ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        NSError *error = nil;
        NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        self.tempArray = fetchedObjects;
        NSLog(@"%@", self.tempArray);
        if (fetchedObjects == nil) {
            
        }else{
            
        }

    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
